﻿using XinLife.Application.Interface;
using XinLife.Model;
using XinLife.Core.Extention;
using XinLife.Core.Model;
using SqlSugar;
using Microsoft.AspNetCore.Mvc;

namespace XinLife.Application.Implement
{
    public class AddressService : BaseService, IAddressService
    {
        public AddressService(IBaseRepository baseRepository) : base(baseRepository) { }
        public Task<List<Region>> GetAllRegions()
        {
            return _db.Queryable<Region>().Where("cLevel in(1,2,3)").ToListAsync();
        }

        public Task<List<Region>> GetRegion(string cRegionCode, int grade, int type = 0)
        {
            string sql = "select * from tb_region where 1=1 ";
            if (!cRegionCode.IsEmpty())
            {
                if (type == 1)//根据区id获取上面的市
                {
                    sql += " and cParentId=(select cParentId from tb_region where cId=(select cParentId from tb_region where cRegionCode = @cRegionCode)) ";
                }
                else if (type == 2) //根据区id获取同级的区
                {
                    sql += " and cParentId=(select cParentId from tb_region where cRegionCode=@cRegionCode) ";
                }
                else if (type == 3)//根据省id获取市   根据市id获取区
                {
                    sql += " and cParentId= (select cId from tb_region where cRegionCode=@cRegionCode)";
                }
            }
            if (!grade.IsEmpty())
            {
                sql += " and cLevel=?grade ";
            }
            return _db.Ado.SqlQueryAsync<Region>(sql, new { cRegionCode, grade });
        }

        public async Task<PageData<Region>> GetRegionPageList(Pagination page, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            string? name = queryParam.Value<string>("name");
            string? code = queryParam.Value<string>("code");
            string? parentId = queryParam.Value<string>("parentId");

            RefAsync<int> totalCount = 0;
            var regions = await _db.Queryable<Region>()
                                 .WhereIF(!name.IsEmpty(), a => a.cRegionName.Contains(name))
                                 .WhereIF(!code.IsEmpty(), a => a.cRegionCode.Contains(code))
                                 .WhereIF(!parentId.IsEmpty(), a => a.cParentId == parentId)
                                 .WhereIF(!name.IsEmpty() && !code.IsEmpty() && !parentId.IsEmpty(), a => a.cLevel == 2)
                                 .ToPageListAsync(page.pageIndex, page.pageSize, totalCount);

            return new PageData<Region>()
            {
                count = totalCount,
                entitys = regions
            };
        }
        public async Task<AjaxResult> GettAddressForm(string id)
        {
            var data = await _db.Queryable<Region>().InSingleAsync(id);
            return Success(data);
        }
        public async Task<AjaxResult> EditRegion(Region region)
        {
            if (region.cParentId == null)
            {
                region.cParentId = "0";
            }

            if (string.IsNullOrWhiteSpace(region.cId))
            {
                var IsExists = await _db.Queryable<Region>().Where(t => t.cRegionCode == region.cRegionCode).ToListAsync();
                if (IsExists.Any())
                {
                    return Error("区划编码不能重复");
                }
                await _db.Insertable(region).ExecuteCommandAsync();
                return Success("添加成功");
            }
            else
            {
                var IsExists = await _db.Queryable<Region>().Where(t => t.cId != region.cId && t.cRegionCode == region.cRegionCode).ToListAsync();
                if (IsExists.Any())
                {
                    return Error("区划编码不能重复");
                }
                var old = await _db.Queryable<Region>().InSingleAsync(region.cId);
                //region.cCreatedBy = old.cCreatedBy;
                region.cCreateDate = old.cCreateDate;
                await _db.Updateable(region).ExecuteCommandAsync();
                return Success("修改成功");
            }
        }

        public async Task<AjaxResult> DelAddress([FromForm] string ids)
        {
            string[] cIds = ids.Split(',');
            var r = await _db.Deleteable<Region>().Where(t => cIds.Contains(t.cId) || cIds.Contains(t.cParentId)).ExecuteCommandAsync();
            if (r > 0)
            {
                return Success("删除成功");
            }
            else
            {
                return Success("删除失败");
            }
        }


    }
}
